﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using com.eforceglobal.crux.DTOs;
using com.eforceglobal.crux.views.Administration;
using com.eforceglobal.crux.views.Enums;
using com.eforceglobal.crux.controllers.Administration;
using com.eforceglobal.crux.DTOs.Configuration;
using com.eforceglobal.crux.controllers;
using com.eforceglobal.crux.configuration;

public partial class Administration_ManageUsers : BaseView, IManageUsers
{
    ManageUsersController _controller = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        int startingRowCount = Convert.ToInt32(CruxConfigurationManager.GetApplicationCustomSetting("PagerSize").Value);
        TableSortSearchPagination1.NumberOfRowsCsv = string.Format("{0},{1},{2},{3}", startingRowCount,
                                                                   startingRowCount * 2, startingRowCount * 4, startingRowCount * 6);
        _controller = new ManageUsersController(this);       
        _controller.InitView(IsPostBack);
        if (!IsPostBack)
        {
            #region Site Map
            SetSiteMap();
            #endregion
            Page.DataBind();
        }        
        if (IsAddUserSupported)
        {
            if (Request.Params["mode"] != null)
            {
                if (Request.Params["mode"].ToLower().Equals("add"))
                {
                    _controller.CreateUser();                    
                }
            }
        }
    }

    #region Site Map
    private void SetSiteMap()
    {
        string query = Request.Url.Query;
        UrlTreeNodeItems.ManageUser = UrlTreeNodeItems.CreateNode("Manage User",
                                                                          "/Administration/ManageUsers.aspx" + query,
                                                                          "ManageUser",
                                                                          UrlTreeNodeItems.ManageMyOrganization);
        UrlTreeNodeItems.SetSiteNavigation(PageSiteMap, UrlTreeNodeItems.ManageUser);
    }
    #endregion
    

    public void grdUsers_RowCommand(object sender, CommandEventArgs e)
    {
        RowCommands rowCommand = (RowCommands)Enum.Parse(typeof(RowCommands), e.CommandName);
        string userId = e.CommandArgument.ToString();

        if (rowCommand == RowCommands.EditItem)
        {
            _controller.OpenUser(int.Parse(userId));
            UrlTreeNodeItems.SetSiteNavigation(PageSiteMap, UrlTreeNodeItems.CreateLeafUrlTreeNode("Edit - " + CurrentUser.FullName, UrlTreeNodeItems.ManageUser));
        }
        else if (rowCommand == RowCommands.DeleteItem)
        {
            _controller.DeleteUser(int.Parse(userId));
        }
        else if (rowCommand == RowCommands.OpenView)
        {
            SessionData sessionData = new SessionData();
            sessionData.PageData = Request.QueryString["id"];
            _controller.ManageUserDetails(int.Parse(userId));
        }
        else if (rowCommand == RowCommands.OpenSecondView)
        {
            _controller.ResetUserPassword(int.Parse(userId));
        }

    }

    protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ImageButton deleteButton = (ImageButton)e.Row.FindControl("btnItemDelete");
            string ReplaceConfirmation = new UILiterals().DeleteUserConfirmation.Replace("{0}",
                DataBinder.Eval(e.Row.DataItem, "UserName").ToString());
            deleteButton.Attributes.Add("onclick", "javascript:return "
                + "confirm('" + ReplaceConfirmation + "')");

            Panel EditPannel = (Panel)e.Row.FindControl("pnlEditUser");
            Panel DeletePannel = (Panel)e.Row.FindControl("pnlDeleteUser");
            Panel ResetUserPasswordPannel = (Panel)e.Row.FindControl("pnlResetUserPassword");
            Panel EditUserDetailPanel = (Panel)e.Row.FindControl("pnlEditUserDetail");
            if (IsEditUserSupported) EditPannel.Visible = true;
            else EditPannel.Visible = false;
            if (IsEditUserDetailSupported) EditUserDetailPanel.Visible = true;
            else EditUserDetailPanel.Visible = false;
            if (IsResetUserPasswordSupported) ResetUserPasswordPannel.Visible = true;
            else ResetUserPasswordPannel.Visible = false;
            if (IsDeleteUserSupported) DeletePannel.Visible = true;
            else DeletePannel.Visible = false;
            if (!IsEditUserSupported && !IsEditUserDetailSupported && !IsResetUserPasswordSupported && !IsDeleteUserSupported)
                grdUsers.Columns[5].Visible = false;
        }
    }


    #region IManageUsers Members

    public List<UserInformation> Users
    {

        set
        {
            grdUsers.DataSource = value;
            grdUsers.DataBind();
        }
    }

    public UserInformation CurrentUser
    {
        get
        {
            UserInformation userInformation = new UserInformation();
            userInformation.UserID = int.Parse(lblUserIDValue.Text);
            userInformation.UserName = txtUserName.Text;
            userInformation.FirstName = txtFirstName.Text;
            userInformation.MiddleName = txtMiddleName.Text;
            userInformation.LastName = txtLastName.Text;
            userInformation.UserComments = txtUserComments.Text;
            userInformation.CompanyID = CompanyID;
            userInformation.CompanyName = _controller.GetCompanyName(CompanyID).CompanyName;
            return userInformation;
        }
        set
        {
            lblUserIDValue.Text = value.UserID.ToString();
            txtUserName.Text = value.UserName;
            txtFirstName.Text = value.FirstName;
            txtMiddleName.Text = value.MiddleName;
            txtLastName.Text = value.LastName;
            txtUserComments.Text = value.UserComments;
        }
    }

    public FormMode FormMode
    {
        get
        {
            if (pnlList.Visible == true)
                return FormMode.List;
            else if (pnlAddEdit.Visible == true)
                return FormMode.AddEdit;
            else
                throw UIExceptions.InvalidFormModeException;
        }
        set
        {
            if (value == FormMode.List)
            {
                pnlList.Visible = true;
                pnlAddEdit.Visible = false;
            }
            else if (value == FormMode.AddEdit)
            {
                pnlList.Visible = false;
                pnlAddEdit.Visible = true;
            }
            else
            {
                throw UIExceptions.InvalidFormModeException;
            }
        }
    }

    #endregion
    protected void btnSave_Click(object sender, EventArgs e)
    {
        _controller.SaveUser();
        #region Site Map
        if (FormMode == FormMode.List)
            SetSiteMap();
        #endregion
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        _controller.CancelAddEdit();
        #region Site Map
        SetSiteMap();
        #endregion
    }
    protected void btnAddNewUser_Click(object sender, EventArgs e)
    {
        _controller.OpenUser(0);
        #region Site Map
        UrlTreeNodeItems.SetSiteNavigation(PageSiteMap, UrlTreeNodeItems.CreateLeafUrlTreeNode("Add", UrlTreeNodeItems.ManageUser));
        #endregion
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        _controller.RedirectToPreviousPage();
    }

    #region IManageUsers Members


    public ErrorInformation ErrorDetails
    {
        get
        {
            return pnlError.ErrorInformation;
        }
        set
        {
            pnlError.ErrorInformation = value;
        }
    }

    public bool IsAddUserSupported
    {
        get { return pnlAddUser.Visible; }
        set { pnlAddUser.Visible = value; }
    }

    public Administration_ManageUsers()
    {
        IsEditUserSupported = false;
        IsEditUserDetailSupported = false;
        IsResetUserPasswordSupported = false;
        IsDeleteUserSupported = false;
    }

    public bool IsEditUserSupported { get; set; }


    #endregion

    #region IManageUsers Members


    public int CompanyID
    {
        get { return int.Parse(Request.Params["id"].ToString()); }
    }


    #endregion

    public bool IsEditUserDetailSupported { get; set; }


    public bool IsResetUserPasswordSupported { get; set; }


    public bool IsDeleteUserSupported { get; set; }

    public bool IsEditUserNameSupported
    {
        set
        {
            txtUserName.Enabled = value;
        }
    }
}
